<template>
    <MyDialog :mode="props.mode" title="Stock Code Version" :submit="submitFn">
        <div class="q-gutter-md q-pa-md">
            <q-input input-class="input-css" borderless v-model="state.data.stock_code" type="text" label="Stock Code"  :readonly="props.mode == 'edit'" />
            <q-input input-class="input-css" borderless v-model="state.data.sw_ver" label="Software Version" type="text"  />
            <q-input input-class="input-css" borderless v-model="state.data.hw_ver" label="Hardware Version" type="text"  />
        </div>
    </MyDialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive } from 'vue'
import { Version } from 'src/services/type'
import { useQuasar } from 'quasar'
import { createVersion, getVersion, patchVersion } from 'src/services/versionService'
import MyDialog from '../container/MyDialog.vue'

export interface VersionFormProp {
    id?: number
    mode: 'create' | 'edit'
    closeable: boolean
}

const emit = defineEmits(['submit', 'close'])

const $q = useQuasar()

const props = withDefaults(defineProps<VersionFormProp>(), {
    mode: 'create',
    stock_code: '',
    closeable: true
})

const state = reactive<{
    data: Version
}>({
    data: {
        id: 0,
        sw_ver: '',
        hw_ver: '',
        stock_code: '',
        update: '',
    }
})

async function initData() {
    if (props.id && props.id>0 && props.mode == 'edit') {
        state.data = await getVersion(props.id)
    }
}

async function create() {
    const data: Partial<Version> = { ...state.data }

    delete data.id
    delete data.update

    const createRes = await createVersion(data)

    if (createRes) {
        $q.notify({
            color: 'positive',
            message: 'Created',
            icon: 'check',
        })
        emit('submit')
        emit('close')
    }
}

async function edit() {
    const data: Partial<Version> = {
        sw_ver: state.data.sw_ver,
        hw_ver: state.data.hw_ver,
    }
    if (props.id) {
        const res = await patchVersion(props.id, data)
        if (res) {
            emit('submit')
            emit('close')
        }
    }
    return
}

function submitFn() {
    if (props.mode == 'create') {
        create()
    } else {
        edit()
    }
}

function closeFn() {
    emit('close')
}


onMounted(() => {
    initData()
})

</script>

<style scoped>
.cap {
    text-transform: capitalize;
}
</style>